package com.xd.core.system.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.LicensePlateValidator;
import com.xd.common.util.SecurityUtil;
import com.xd.core.api.mapper.AdvancePaymentOrderMapper;
import com.xd.core.api.mapper.ChannelPayTowMapper;
import com.xd.core.business.entity.CarCredit;
import com.xd.core.business.entity.GuaranteeSlip;
import com.xd.core.business.entity.Information;
import com.xd.core.business.listener.ImportCarCreditListener;
import com.xd.core.business.mapper.*;
import com.xd.core.business.service.ICarCreditService;
import com.xd.core.company.mapper.ChannelTowRechargeMapper;
import com.xd.core.company.mapper.CompanyMapper;
import com.xd.core.debt.mapper.DebtMapper;
import com.xd.core.system.dto.DeleteBatchFilesDto;
import com.xd.core.system.dto.DeleteEndorsementUrlDto;
import com.xd.core.system.dto.DownloadAttachmentDto;
import com.xd.core.system.entity.SysUser;
import com.xd.core.system.mapper.SysUserMapper;
import com.xd.core.system.service.FileService;
import com.xd.core.system.vo.ImageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Api(tags = "上传功能")
@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileService fileService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ICarCreditService iCarCreditService;
    @Value("${image.agencyCompany}")
    private String agencyCompany;//公司新建代理-上传代理文件
    @Value("${image.blocCompany}")
    private String blocCompany;//公司新建代理-上传代理文件
    @Value("${image.balance}")
    private String balance;//服务费-上传收费凭证
    @Value("${image.paymentVoucher}")
    private String paymentVoucher;//业务账户充值-打款凭证
    @Value("${image.capitalCompany}")
    private String capitalCompany;//平台新建资方-上传资方文件
    @Value("${image.uploadHead}")
    private String uploadHead;//上传头像
    @Value("${image.uploadIdCard}")
    private String uploadIdCard;//上传员工身份证
    @Value("${image.customerInfo}")
    private String uploadCustomerInfo;//上传客户资产信息
    @Value("${image.uploadMortgageInfo}")
    private String uploadMortgageInfo;//上传客户抵押信息
    @Value("${image.product}")
    private String productLogo;//上传产品logo
    @Value("${image.bookkeeping}")
    private String bookkeeping;//上传客户还款凭证
    @Value("${image.carCredit}")
    private String carCredit;//上传保单贷车辆信息
    @Value("${image.guaranteeSlip}")
    private String guaranteeSlip;//上传保单信息
    @Value("${image.endorsement}")
    private String endorsement;//上传保单信息
    @Value("${image.printed}")
    private String printed;//上传用印申请
    @Value("${image.advancePaymentVoucher}")
    private String advancePaymentVoucher;//预付款凭证
    @Value("${image.towWithdrawDeposit}")
    private String towWithdrawDeposit;//渠道二汇款账户提现凭证
    @Value("${image.refundVoucher}")
    private String refundVoucher;

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private InformationMapper informationMapper;
    @Autowired
    private AdvancePaymentOrderMapper advancePaymentOrderMapper;
    @Autowired
    private ChannelPayTowMapper channelPayTowMapper;
    @Autowired
    private ChannelTowRechargeMapper channelTowRechargeMapper;
    @Autowired
    private IncomingInfoMapper incomingInfoMapper;
    @Autowired
    private DebtMapper debtMapper;
    @Autowired
    private GuaranteeSlipMapper guaranteeSlipMapper;
    @Autowired
    private OutInfoMapper outInfoMapper;
    @Autowired
    private SurrenderinfoMapper surrenderinfoMapper;


    //实现文件删除的功能
    @ApiOperation(value = "删除图片/文件")
    @DeleteMapping("/deleteFile")
    public String fileRemove(String virtualPath) {

        fileService.fileRemove(virtualPath);
        return "删除成功";
    }

    @ApiOperation(value = "删除合作合同")
    @Transactional
    @DeleteMapping("/deleteContract")
    public String fileRemoveContract(@RequestParam("virtualPath") String virtualPath,
                                     @RequestParam("companyId") Integer companyId) {
        companyMapper.updateContract(companyId, null);
        fileService.fileRemove(virtualPath);
        return "删除成功";
    }

    //删除文件夹
    @ApiOperation(value = "删除文件夹")
    @DeleteMapping("/deleteFolder")
    public String deleteFolder(String virtualPath) {

        fileService.deleteFolder(virtualPath);
        return "删除文件夹成功";
    }

    @ApiOperation(value = "批量删除图片/文件")
    @PostMapping("/deleteBatchFiles")
    public String filesRemove(@RequestBody List<String> virtualPaths) {
        fileService.filesRemove(virtualPaths);
        return "批量删除成功";
    }

    //    @ApiOperation(value = "下载文件")
    @PostMapping("/downloadCustomerAttachment")
    public void downloadCustomerAttachment(@RequestBody DownloadAttachmentDto downloadAttachmentDto, HttpServletResponse response) {
        fileService.downloadCustomerAttachment(downloadAttachmentDto.getPath().get(0), response);
    }

    //    @ApiOperation(value = "打包批量下载")
    @PostMapping("/downloadToPack")
    public void downloadToPack(@RequestBody DownloadAttachmentDto downloadAttachmentDto, HttpServletResponse response) {
        fileService.downloadToPack(downloadAttachmentDto.getPath(), response);
    }

    @ApiOperation(value = "资方新建代理——上传代理文件")
    @PostMapping("/uploadAgencyCompany")
    public ImageVO uploadAgencyCompany(MultipartFile file) throws IOException {
        String path = agencyCompany + "/" + SecurityUtil.getLoginCompanyId() + "/dl/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }

    @ApiOperation(value = "资方新建代理——上传合作合同")
    @PostMapping("/cooperativeContract/{companyId}")
    public ImageVO cooperativeContract(@PathVariable Integer companyId, @RequestPart("file") MultipartFile file) throws IOException {
        String path = agencyCompany + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        companyMapper.updateContract(companyId, imageVO.getVirtualPath());
        return imageVO;
    }

    @ApiOperation(value = "平台新建集团——上传合作合同")
    @PostMapping("/blocCooperativeContract/{companyId}")
    public ImageVO blocCooperativeContract(@PathVariable Integer companyId, @RequestPart("file") MultipartFile file) throws IOException {
        String path = blocCompany + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        companyMapper.updateContract(companyId, imageVO.getVirtualPath());
        return imageVO;
    }

    @ApiOperation(value = "平台新建资方——上传代理文件")
    @PostMapping("/uploadCapitalCompany")
    public ImageVO uploadCapitalCompany(MultipartFile file) throws IOException {
        String path = capitalCompany + "/pt/zf/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }

    @ApiOperation(value = "上传员工头像")
    @PostMapping("/uploadHead")
    public ImageVO uploadHead(MultipartFile file) throws IOException {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        String path = null;
        if (companyType.equals(SysConstant.COMPANY_TYPE_ONE)) {
            path = uploadHead + "/pt/";
        } else {
            path = uploadHead + "/" + SecurityUtil.getLoginCompanyId() + "/";
        }
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }

    @ApiOperation(value = "个人信息修改头像")
    @PostMapping("/oneselfUploadHead")
    public ImageVO oneselfUploadHead(MultipartFile file) throws IOException {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        String path = null;
        if (companyType.equals(SysConstant.COMPANY_TYPE_ONE)) {
            path = uploadHead + "/pt/";
        } else {
            path = uploadHead + "/" + SecurityUtil.getLoginCompanyId() + "/";
        }
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        //删除老头像
        String avatar = sysUserMapper.selectById(SecurityUtil.getLoginUserId()).getAvatar();
        if (avatar != null) {
            fileService.fileRemove(avatar);
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(SecurityUtil.getLoginUserId());
        sysUser.setAvatar(imageVO.getVirtualPath());
        sysUserMapper.updateById(sysUser);
        return imageVO;
    }

    @ApiOperation(value = "上传员工身份证")
    @PostMapping("/uploadIdCard")
    public ImageVO uploadIdCard(MultipartFile file) throws IOException {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        String path = null;
        if (companyType.equals(SysConstant.COMPANY_TYPE_ONE)) {
            path = uploadIdCard + "/pt/";
        } else {
            path = uploadIdCard + "/" + SecurityUtil.getLoginCompanyId() + "/";
        }
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }

    @ApiOperation(value = "进件--上传资料")
    @PostMapping("/uploadCustomerInfo")
    public ImageVO upload(MultipartFile file) throws IOException {
        Integer companyId = SecurityUtil.getLoginCompanyId();
        String path = uploadCustomerInfo + "/annex/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }


    @ApiOperation(value = "进件--上传抵押资料")
    @PostMapping("/uploadMortgageInfo/{companyId}")
    public ImageVO uploadMortgageInfo(@PathVariable Integer companyId, @RequestPart("file") MultipartFile file) throws IOException {
        String path = uploadMortgageInfo + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }


    @ApiOperation(value = "还款记账--收款凭证")
    @PostMapping("/bookkeeping/{companyId}")
    public ImageVO bookkeeping(@PathVariable Integer companyId, @RequestPart("file") MultipartFile file) throws IOException {
        String path = bookkeeping + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }


    @ApiOperation(value = "服务费充值--打款凭证")
    @PostMapping("/balance/{companyId}")
    public ImageVO balance(@PathVariable Integer companyId, @RequestPart("file") MultipartFile file) throws IOException {
        String path = balance + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }

        return imageVO;
    }

    @ApiOperation(value = "产品--上传产品logo")
    @PostMapping("/uploadProductLogo")
    public ImageVO uploadProductLogo(@RequestPart("file") MultipartFile file) throws IOException {
        String path = uploadCustomerInfo + "/" + productLogo + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }

    @ApiOperation(value = "保单管理--上传保单或批单")
    @PostMapping("/guaranteeSlip/{guaranteeId}/{type}")
    public ImageVO guaranteeSlip(@PathVariable Integer guaranteeId, @PathVariable String type, @RequestPart("file") MultipartFile file) throws IOException {
        String path = "";
        ImageVO imageVO = new ImageVO();
        if ("1".equals(type)) {
            path = guaranteeSlip + "/" + guaranteeId + "/";
        } else {
            path = endorsement + "/" + guaranteeId + "/";
        }
        String filename = file.getOriginalFilename();
        //根据保单id获取保单数据
        LambdaQueryWrapper<GuaranteeSlip> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GuaranteeSlip::getId, guaranteeId);
        GuaranteeSlip guaranteeSlip = guaranteeSlipMapper.selectOne(wrapper);
        //获取旧的保单文件路径
        String oldFilePathUrl = guaranteeSlip.getGuaranteeSlipUrl();
        if (ObjectUtil.isEmpty(guaranteeSlip))
            throw new XkdException("该车辆保单不存在");
        //判断是上传保单还是上传批单
        if ("1".equals(type)) {
            String[] parts = filename.split("-");
            String carNo = "";
            String policyNumber = "";
            //校验文件命名是否规范
            if (parts.length == 0 || parts == null || parts.length != 2) {
                throw new XkdException("未按照规则命名文件");
            }
            // 提取车牌号
            carNo = parts[0];
            //校验车牌号
            if (!LicensePlateValidator.isValidChineseLicensePlate(carNo)) {
                throw new XkdException("车牌号格式错误");
            }
            //已复核的保单不允许修改保单
            if (guaranteeSlip.getReviewStatus().equals(1)) {
                throw new XkdException("该保单已复核,不允许修改保单");
            }
            //判断车牌号是否一致
            if(!guaranteeSlip.getCarNo().equals(carNo)){
                throw new XkdException("车牌号不一致");
            }
            // 提取保单号
            policyNumber = parts[1].substring(0, parts[1].length() - 4);
            //上传文件到服务器
            imageVO = fileService.uploadSinglePolicy(file, path);
            //构建新的保单数据
            guaranteeSlip.setGuaranteeSlipUrl(imageVO.getVirtualPath());
            guaranteeSlip.setPolicyNo(policyNumber);
            guaranteeSlip.setUploadUser(SecurityUtil.getLoginUser().getUser().getUserName());
            guaranteeSlip.setUploadDate(new Date());
            //更新新的保单数据
            guaranteeSlipMapper.updateById(guaranteeSlip);
            //删除服务器中的旧的保单文件
            if (StrUtil.isNotEmpty(oldFilePathUrl)) {
                fileService.fileRemove(oldFilePathUrl);
            }
        } else {
            //上传文件到服务器
            imageVO = fileService.uploadSinglePolicy(file, path);
            guaranteeSlip.setEndorsementUrl(ObjectUtil.isEmpty(guaranteeSlip.getEndorsementUrl()) ? imageVO.getVirtualPath() : guaranteeSlip.getEndorsementUrl() + "," + imageVO.getVirtualPath());
        }
        return imageVO;
    }

    /*
     * 渠道二充值--上传打款凭证
     * */
    @ApiOperation(value = "业务账户充值--上传打款凭证")
    @PostMapping("/uploadPaymentVoucher")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "渠道二充值记录id", dataType = "int"),
            @ApiImplicitParam(name = "companyId", value = "公司ID", dataType = "int")
    })
    public ImageVO uploadPaymentVoucher(@RequestParam Integer companyId, @RequestParam(required = false) Integer id, @RequestParam("file") MultipartFile file) throws IOException {
        String path = paymentVoucher + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        if (id != null) {//代表在列表上上传
            channelTowRechargeMapper.updateVoucher(id, imageVO.getVirtualPath());
        }
        return imageVO;
    }

    @ApiOperation(value = "保单贷--上传车辆信息")
    @PostMapping("/uploadCarCredit/{id}")
    public ImageVO uploadCarCredit(@PathVariable Integer id, @RequestPart("file") MultipartFile file) throws IOException {
        String path = carCredit + "/" + id + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        return imageVO;
    }

    @PostMapping("/uploadGuaranteeSlips")
    @ApiOperation(value = "保单贷--批量上传保单")
    public List<String> uploadZip(@RequestParam("zipFile") MultipartFile file, @RequestParam String incomingOrder) {
        List<String> list = fileService.uploadZipForPolicy(file, incomingOrder);
        return list;
    }

    @PostMapping("/replaceFile")
    @ApiOperation(value = "替换文件（用印资料上传）")
    public void replaceFile(@RequestParam("File") MultipartFile file, @RequestParam String virtualPath, @RequestParam String uid) throws IOException {
        fileService.replaceFile(file, virtualPath, uid);
    }

    @PostMapping("/uploadPrintedMaterials/{incomingId}/{typeOfSealUsed}/{uid}")
    @ApiOperation(value = "用印申请（用印资料上传）")
    public ImageVO uploadPrintedMaterials(@RequestParam("File") MultipartFile file, @PathVariable Integer incomingId, @PathVariable String typeOfSealUsed, @PathVariable String uid) throws IOException {
        String path = printed + "/" + incomingId + "/" + typeOfSealUsed + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        Information information = new Information();
        information.setFileName(imageVO.getFileName());
        information.setInformationUrl(imageVO.getVirtualPath());
        information.setIncomingId(incomingId);
        information.setUploadTime(new Date());
        information.setTypeOfSealUsed(typeOfSealUsed);
        information.setUid(uid);
        informationMapper.insert(information);
        return imageVO;
    }

    @PreAuthorize("hasAnyAuthority('sys:PolicyDisbursement-UploadCredentials','sys:GuaranteeDetail-UploadCredentials')")
    @PostMapping("/advancePaymentVoucher")
    @ApiOperation(value = "上传银行转账预付款凭证")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "orderNo", value = "预付款订单号", dataType = "string"),
            @ApiImplicitParam(name = "companyId", value = "公司ID", dataType = "int"),
            @ApiImplicitParam(name = "incomingId", value = "进件ID", dataType = "int"),
            @ApiImplicitParam(name = "tradeTime", value = "到账时间", dataType = "string")
    })
    public String advancePaymentVoucher(@RequestParam("File") MultipartFile[] files, @RequestParam String orderNo, @RequestParam Integer companyId, @RequestParam Integer incomingId, @RequestParam String tradeTime) throws IOException {
        String path = advancePaymentVoucher + "/" + companyId + "/";
        StringBuilder stringBuilder = new StringBuilder();
        for (MultipartFile file : files) {
            ImageVO imageVO = fileService.upload(file, path);
            if (imageVO == null) {
                throw new XkdException("上传失败");
            }
            stringBuilder.append(imageVO.getVirtualPath()).append(",");
        }
        String string = stringBuilder.toString();
        String substring = string.substring(0, string.length() - 1);
        //查询是否有预付款记录
        advancePaymentOrderMapper.updateVoucher(orderNo, substring, tradeTime);
        incomingInfoMapper.updateStatus(SysConstant.BUSINESS_STATUS_ELEVEN, incomingId);
        //修改预付款状态
        outInfoMapper.updateAdvanceStatus(incomingId);
        return substring;
    }


    @PostMapping("/towWithdrawDeposit")
    @ApiOperation(value = "上传渠道二回款账户提现凭证")
    public ImageVO towWithdrawDeposit(@RequestParam("File") MultipartFile file, @RequestParam(required = false) String orderNo, @RequestParam Integer companyId) throws IOException {
        String path = towWithdrawDeposit + "/" + companyId + "/";
        ImageVO imageVO = fileService.upload(file, path);
        if (imageVO == null) {
            throw new XkdException("上传失败");
        }
        if (StringUtils.isNotBlank(orderNo)) {//代表在列表上上传
            channelPayTowMapper.updateVoucher(orderNo, imageVO.getVirtualPath());
        }
        return imageVO;
    }

    @ApiOperation(value = "批量删除用印资料并删除数据库数据")
    @PostMapping("/deleteBatchPrintFiles")
    public String filesRemove(@RequestBody DeleteBatchFilesDto dto) {
        fileService.filesRemove(dto.getVirtualPaths());
        //删除数据库中得数据
        informationMapper.deleteBatchFiles(dto);
        return "批量删除成功";
    }

    @ApiOperation(value = "删除批单数据并删除数据库数据")
    @PostMapping("/deleteEndorsementUrl")
    public String filesRemoveEndorsementUrl(@RequestBody DeleteEndorsementUrlDto dto) {
        //删除文件
        fileService.fileRemove(dto.getVirtualPath());
        //删除数据库中得数据
        GuaranteeSlip slip = guaranteeSlipMapper.selectById(dto.getGuaranteeId());
        String endorsementUrl = slip.getEndorsementUrl();
        if (ObjectUtil.isNotEmpty(endorsementUrl)) {
            String[] pathArray = endorsementUrl.split(",");
            StringBuilder result = new StringBuilder();
            for (String path : pathArray) {
                if (!path.equals(dto.getVirtualPath())) {
                    if (result.length() > 0) {
                        result.append(",");
                    }
                    result.append(path);
                    log.info("执行批单文件删除");
                }
            }
            slip.setEndorsementUrl(result.toString());
            guaranteeSlipMapper.updateById(slip);
        }
        return "删除批单文件成功";
    }

    @PreAuthorize("hasAnyAuthority('sys:GuaranteeDetail-uploadVoucher')")
    @PostMapping("/refundVoucher/{surrenderId}")
    @ApiOperation(value = "上传退保凭证")
    public List<ImageVO> refundVoucher(@RequestParam("files") MultipartFile[] files, @PathVariable Integer surrenderId) throws IOException {
        String path = refundVoucher + "/" + surrenderId + "/";
        List<ImageVO> result = new ArrayList<>();
        for (MultipartFile file : files) {
            ImageVO imageVO = fileService.upload(file, path);
            if (imageVO == null) {
                throw new XkdException("文件上传失败: " + file.getOriginalFilename());
            }
            informationMapper.insertRefundVoucher(imageVO.getVirtualPath(), surrenderId, imageVO.getFileName());
            result.add(imageVO);
        }
        //设置上传退保凭证标记并修改状态为已退保
        surrenderinfoMapper.setRefundVoucherAndStatus(surrenderId);
        //根据id获取退保时选择的保单
        String policyNo = surrenderinfoMapper.getPolicyNo(surrenderId);
        List<String> policyList = Arrays.asList(policyNo.split(","));
        //将本次退保中的保单状态修改为已退保
        guaranteeSlipMapper.updateStatus(policyList);
        return result;
    }

    @ApiOperation("导入车辆信息模板")
    @PostMapping("/importReceive/{incomingId}")
    public Map<String, Integer> importReceive(@RequestPart MultipartFile file, @PathVariable Integer incomingId) {
        TreeMap<String, Integer> map = new TreeMap<>();
        try {
            InputStream inputStream = file.getInputStream();
            ImportCarCreditListener importUnReceiveListener = new ImportCarCreditListener(iCarCreditService, incomingId);
            ExcelReaderBuilder read = EasyExcel.read(inputStream, CarCredit.class, importUnReceiveListener);
            ExcelReaderSheetBuilder sheet = read.sheet();
            sheet.doRead();
            map = importUnReceiveListener.getMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @ApiOperation("批量上传行驶证")
    @PostMapping("/importDriving/{incomingId}")
    public void importDriving(@RequestPart MultipartFile file, @PathVariable Integer incomingId) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new XkdException("上传文件不能为空");
        }

        // 检查文件是否为ZIP格式
        String fileName = file.getOriginalFilename();
        if (!fileName.toLowerCase().endsWith(".zip")) {
            throw new XkdException("请上传ZIP格式的压缩包");
        }

        // 处理上传的文件
        iCarCreditService.processDrivingZipFile(file, incomingId);
    }

    @ApiOperation("批量上传投保单")
    @PostMapping("/importInsuranceApl/{incomingId}")
    public void importInsuranceApl(@RequestPart MultipartFile file, @PathVariable Integer incomingId) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new XkdException("上传文件不能为空");
        }

        // 检查文件是否为ZIP格式
        String fileName = file.getOriginalFilename();
        if (!fileName.toLowerCase().endsWith(".zip")) {
            throw new XkdException("请上传ZIP格式的压缩包");
        }

        // 处理上传的文件
        iCarCreditService.processInsuranceAplZipFile(file, incomingId);
    }
}